package com.syq.play.service;

import java.io.IOException;
import java.util.List;

import com.syq.play.AppContent;
import com.syq.play.R;
import com.syq.play.model.MediaModel;
import com.syq.play.ui.SRPlayActivity;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.provider.MediaStore.Audio.Media;
import android.util.Log;
import android.widget.Toast;

public class LocalService extends Service { 
	public static final String ID="id";
	private static final String TAG="LocalService";
    private MediaPlayer mPlayer;
	private Notification notification;
	private PhoneReceiver phoneReceiver;
	private boolean isPlay;
	private String path, title, artist;
	private int position;
	public  static List<MediaModel> listData;
	
    IPlayer.Stub stub = new IPlayer.Stub() {
    	@Override
		public void play() throws RemoteException {
    		if(mPlayer!=null ){
    			mPlayer.start();
    			isPlay=true;
    		}
			
		}
		@Override
		public void pause() throws RemoteException {
			if(mPlayer!=null && mPlayer.isPlaying()){
				mPlayer.pause();
				isPlay=false;
			}
		}

		@Override
		public void stop() throws RemoteException {
			if(mPlayer!=null){
				mPlayer.stop();
				isPlay=false;
			}
		}

		@Override
		public int getDuration() throws RemoteException {
			return mPlayer.getDuration();
		}

		@Override
		public int getCurrentTime() throws RemoteException {
			return mPlayer.getCurrentPosition();
		}

		@Override
		public void setCurrent(int cur) throws RemoteException {
			mPlayer.seekTo(cur);
		}

		@Override
		public boolean isPlaying() throws RemoteException {
			if(mPlayer==null){
				return false;
			}
			return mPlayer.isPlaying();
		}
		@Override
		public void setPlayPosition(int position) throws RemoteException {
			LocalService.this.position=position;
			listData=AppContent.listData;
			if(listData!=null && !listData.isEmpty()){
				setMeidaData(position, listData);
			}
		}
		private void setMeidaData(int position, List<MediaModel> listData){
			MediaModel media=listData.get(position);
			title=media.getMediaTitle();
			artist=media.getMediaArtist();
			path=media.getMediaData();
			showNotification(title, artist);
			if(mPlayer!=null){
				mPlayer.stop();
				mPlayer.release();
			}
			mPlayer = new MediaPlayer();
	        try {
				mPlayer.setDataSource(path);
				mPlayer.prepare();
				mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
					@Override
					public void onCompletion(MediaPlayer mp) {
						try {
							playNext();
							isPlay=true;
						} catch (RemoteException e) {
							e.printStackTrace();
						}
					}
				});
	        } catch (IllegalArgumentException e1) {
				e1.printStackTrace();
			} catch (IllegalStateException e1) {
				e1.printStackTrace();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
	        Intent intent=new Intent();
	        intent.setAction(SRPlayActivity.ACTION_PREV_NEXT);
	        Bundle data=new Bundle();
	        data.putInt(ID, media.getMediaId());
	        intent.putExtras(data);
	        sendBroadcast(intent);
		}
		@Override
		public boolean isPrepare() throws RemoteException {
			if(mPlayer==null){
				return false;
			}
			return true;
		}
		@Override
		public void showNotif(String title, String name) throws RemoteException {
			showNotification(title, name);
		}
		@Override
		public void cancelNotif() throws RemoteException {
			cancelNotification();
		}
		@Override
		public String getPath() throws RemoteException {
			return path;
		}
		@Override
		public String getTitle() throws RemoteException {
			return title;
		}
		@Override
		public String getArtist() throws RemoteException {
			return artist;
		}
		@Override
		public void playNext() throws RemoteException {
			if(listData!=null){
				int size=listData.size();
				if(size>0){
					position++;
					position=position%size;
					setMeidaData(position, listData);
					play();
				}
				
			}
		}
		@Override
		public void playPre() throws RemoteException {
			if(listData!=null){
				int size=listData.size();
				if(size>0){
					position=position+size-1;
					position=position%size;
					setMeidaData(position, listData);
					play();
				}
			}
		}
    };
    @Override 
    public void onCreate() { 
    	super.onCreate();
        Log.i(TAG, "onCreate……");
        phoneReceiver=new PhoneReceiver();
        IntentFilter filter=new IntentFilter();
        filter.addAction("android.intent.action.PHONE_STATE");
        filter.addAction("android.intent.action.NEW_OUTGOING_CALL");
        registerReceiver(phoneReceiver, filter);
    } 
    @Override
    public void onDestroy() {
    	super.onDestroy();
    	Log.i(TAG, "onDestroy……");
    	if(phoneReceiver!=null){
    		unregisterReceiver(phoneReceiver);
    	}
    }
 
    public int onStartCommand(Intent intent, int flags, int startId) { 
        Log.i("LocalService", "Received start id " + startId + ": " + intent); 

        return START_STICKY; 
    } 
 
    @Override 
    public IBinder onBind(Intent intent) { 
        return stub; 
    } 
    private void showNotification(String title, String name){
		notification = new Notification(R.drawable.ic_launcher,
				title, System.currentTimeMillis());
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
		        new Intent(this, SRPlayActivity.class), 0);
		notification.setLatestEventInfo(this, title,
		        name, contentIntent);
		notification.icon=R.drawable.notif_icon;
		notification.flags=Notification.FLAG_ONGOING_EVENT;
		startForeground(1, notification);
	}
    private void cancelNotification(){
    	stopForeground(true);
    }
    class PhoneReceiver extends BroadcastReceiver {
    	private static final String TAG = "PhoneReceiver";

    	@Override
    	public void onReceive(Context context, Intent intent) {
    		if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
    			String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
    			Log.d(TAG, "拨打号码:" + phoneNumber);
    			
    		} else {
    			String s = intent.getStringExtra("state");
    			if ("OFFHOOK".equals(s) || "RINGING".equals(s)) {
    				Log.i(TAG, "-----通话中-------");
    				if(mPlayer!=null && mPlayer.isPlaying())
    					mPlayer.pause();
    			} else {
    				
    				Log.i(TAG, "-----通话完成-------");
    				if(mPlayer!=null && !mPlayer.isPlaying() && isPlay)
            			mPlayer.start();
    			}
    		}
    	}
    }
 }